import os

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util, template

from ixapi.db import SimpleListDB, FilesDB

class MainHandler(webapp.RequestHandler):

  def get(self):
    self.response.out.write('Hello world!')

class SimpleList(webapp.RequestHandler):

  def get(self):
    listDb = SimpleListDB.all().order('-created')
    view_list = os.path.join(os.path.dirname(__file__), 'view/manager/SimpleList.htm')
    view_list_values = {
      'lists': listDb,
      }
    self.response.out.write(template.render(view_list, view_list_values))
    
class SimpleListAdd(webapp.RequestHandler):

  def post(self):
    listDb = SimpleListDB()
    listDb.title = self.request.get('title')
    listDb.put()
    self.redirect('/manager/simplelist')

class SimpleListDel(webapp.RequestHandler):

  def get(self, key = ''):
    if(key):
      dellist = db.get(db.Key(key))
      dellist.delete()
    self.redirect('/manager/simplelist')

class FileList(webapp.RequestHandler):

  def get(self):
    listDb = FilesDB.all().order('-created')
    view_list = os.path.join(os.path.dirname(__file__), 'view/manager/FileList.htm')
    view_list_values = {
      'lists': listDb,
      }
    self.response.out.write(template.render(view_list, view_list_values))

class FileListAdd(webapp.RequestHandler):

  def post(self):
    fileblob = self.request.get("file")
    filetype = self.request.body_file.vars['file'].headers['content-type']
    filesize = len(fileblob)
    files = FilesDB(type = filetype, size = filesize)
    
    files.title = self.request.get("title")
    files.desc = self.request.get("desc")
    
    if filetype.find("image") != -1:
      files.isimage = True
    else:
      files.isimage = False
    files.file = db.Blob(fileblob)
    files.put()
    self.redirect('/manager/filelist')
    
def main():
  application = webapp.WSGIApplication([('/manager', MainHandler),
                                    ('/manager/', MainHandler),
                                    ('/manager/simplelist', SimpleList),
                                    ('/manager/simplelistadd', SimpleListAdd),
                                    ('/manager/simplelistdel/([0-9a-zA-Z\-]+)', SimpleListDel),
                                    ('/manager/filelist', FileList),
                                    ('/manager/filelistadd', FileListAdd)
                                    ],
                                       debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
